import type { SortOrder } from "mongoose";
export default defineEventHandler(async (event) => {
  const queryObj = getQuery(event);
  const { orderBy = "createdAt", order = "desc" } = queryObj;
  const customSort = {
    [orderBy as string]: order as SortOrder,
  };
  const currentPage = Number(queryObj.currentPage) || 1;
  const pageSize = Number(queryObj.pageSize) || 10;
  const skip = (currentPage - 1) * pageSize;
  const findCondition: {
    [key: string]: any;
  } = {};
  if (queryObj.account) {
    findCondition.account = {
      // 模糊匹配
      $regex: queryObj.account,
    };
  }
  if (queryObj.name) {
    findCondition.name = {
      // 模糊匹配
      $regex: queryObj.name,
    };
  }
  if (queryObj.nickName) {
    findCondition.nickName = {
      // 模糊匹配
      $regex: queryObj.nickName,
    };
  }
  if (queryObj.department) {
    findCondition.department = queryObj.department;
  }
  if (queryObj.age) {
    findCondition.age = queryObj.age;
  }
  if (queryObj.address) {
    findCondition.address = {
      // 模糊匹配
      $regex: queryObj.address,
    };
  }
  if (queryObj.createdAt_start && queryObj.createdAt_end) {
    findCondition.createdAt = {
      $gte: new Date(queryObj.createdAt_start as string),
      $lte: new Date(queryObj.createdAt_end as string),
    };
  }
  const userList = await UserSchema.find(findCondition)
    .select([
      "account",
      "name",
      "nickName",
      "age",
      "address",
      "createdAt",
      "updatedAt",
      "disabled",
      "roles",
      "department",
      "positions",
      "gender",
      "avatar",
    ])
    .skip(skip)
    .limit(pageSize)
    .sort(customSort)
    .lean();
  const total = await UserSchema.find(findCondition).countDocuments();
  return {
    data: userList,
    total,
    pageSize,
    currentPage,
  };
});
